package com.service;


import com.alibaba.fastjson.JSONObject;
import com.util.WeixinUtil;
import com.vo.WxLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

@Service
public class WxLoginService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${weixin.appid}")
    private  String appid;

    @Value("${weixin.secret}")
    private  String secret;

    public int saveOrUpdateWeixinInfo(String code, String nick, String head,String miwen,String iv) throws UnsupportedEncodingException {
        //获取openID要传appid,secret,code
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        String newUrl = String.format(url,appid,secret,code);
        String result = restTemplate.getForObject(newUrl,String.class);
        //String openId =JSONObject.parseObject(result).getString("openid");

        WxLoginVO vo = JSONObject.parseObject(result,WxLoginVO.class);
        System.out.println(vo.getOpenid());
        System.out.println(vo.getSession_key());
        String sessionKey = vo.getSession_key();



        String str = WeixinUtil.decryptData(miwen,sessionKey,iv);
        System.out.println(str);

        return 0;
    }
}
